import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MyFrame extends JFrame {
	private MyQueue<Integer> queue;

	private JTextField text0;
	private JTextField text1;
	private JTextField text2;
	private JTextField text3;
	private JTextField text4;

	public MyFrame() {
		super("Queue test");
		createGUI();
	}

	public void refresh() {
		text1.setText("Queue contents: " + queue.print());
		if (!queue.empty())
			text2.setText("Front: " + queue.front());
		else
			text2.setText("Front:");
		if (!queue.empty())
			text3.setText("Back: " + queue.back());
		else
			text3.setText("Back:");
		text4.setText("Size: " + queue.size());
	}

	public void createGUI() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout());

		JButton button1 = new JButton("Push");
		button1.setActionCommand("1");
		panel.add(button1);

		JButton button2 = new JButton("Pop");
		button2.setActionCommand("2");
		panel.add(button2);

		text0 = new JTextField();
		text0.setColumns(50);
		text0.setActionCommand("1");
		text1 = new JTextField();
		text1.setColumns(50);
		text2 = new JTextField();
		text2.setColumns(50);
		text3 = new JTextField();
		text3.setColumns(50);
		text4 = new JTextField();
		text4.setColumns(50);

		panel.add(text0);
		panel.add(text1);
		panel.add(text2);
		panel.add(text3);
		panel.add(text4);

		ActionListener actionListener = new TestActionListener();

		text0.addActionListener(actionListener);
		button1.addActionListener(actionListener);
		button2.addActionListener(actionListener);

		getContentPane().add(panel);
		setPreferredSize(new Dimension(730, 200));

		queue = new MyQueue<Integer>();
		refresh();
	}

	public class TestActionListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			try {
				if (e.getActionCommand() == "1") {
					queue.push(Integer.parseInt(text0.getText()));
					text0.setText("");
					refresh();
					return;
				}
				if (e.getActionCommand() == "2") {
					queue.pop();
					refresh();
					return;
				}
			} catch (NumberFormatException nfe) {
				text0.setText("");
			}

		}
	}

	public static void main(String[] args) {

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame.setDefaultLookAndFeelDecorated(true);
				MyFrame frame = new MyFrame();
				frame.pack();
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		});
	}
}